package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;

import com.api.shopapi.entity.*;
import com.api.shopapi.service.UserService;
import com.api.shopapi.service.VerificationCodeLimitService;
import com.api.shopapi.service.VerificationCodeService;
import com.api.shopapi.util.smsTencent.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("VerificationCode")
public class VerificationCodeController extends  BaseController{

    @Autowired
    private HttpServletRequest request;

    @Autowired
    @Qualifier("VerificationCodeServiceImplOne")
    private VerificationCodeService verificationCodeService;

    @Autowired
    @Qualifier("VerificationCodeLimitServiceImplOne")
    private VerificationCodeLimitService verificationCodeLimitService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;



    //注册验证码
    @RequestMapping(value = "RegCode",method = RequestMethod.POST)
    public MyResult RegCode(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String phone = jsonObject.getString("phone");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/VerificationCode/RegCode");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            HttpServletRequest request2 =
                    ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();


            String ip = getIpAddress(request);
            if(ip == null || ip.equals("")){
                return failed("ip地址错误");
            }

            if(!isPhone(phone)){
                return failed("手机号格式错误");
            }

            User user = userService.getByPhone(phone);
            if(user != null){
                return failed("手机号已注册");
            }

            String code = Integer.toString(random());

            SendSms sendSms = new SendSms();
            sendSms.SendSms("银秋科技","1102217",phone,code);

            /*
            * 首先判断客户端ip是否发送过验证码
            * 1：未发送过
            *   直接发送
            * 2：发送过
            *   今日是否发送过验证码
            *   2.1今日发送给验证码
            *       发送数量是否超过200个
            *       2.1.1超过了，提示超过上限
            *       2.1.2未超过，直接发送
            *   2.2今日未发送过验证码
            *      直接发送
            *
            * */



            VerificationCodeLimit verificationCodeLimit = verificationCodeLimitService.getByIP(ip);

            if(verificationCodeLimit == null){
                //该ip未发送过验证码

                verificationCodeLimit = new VerificationCodeLimit();
                verificationCodeLimit.setVerificationCodeLimitCode(UUID.randomUUID().toString());
                verificationCodeLimit.setIp(ip);
                verificationCodeLimit.setCount(1);
                verificationCodeLimit.setCreateTime(new Date());
                verificationCodeLimitService.insert(verificationCodeLimit);

                VerificationCode verificationCode = verificationCodeService.getByPhone(phone);
                if(verificationCode == null){
                    //该phone未发送过验证码
                    verificationCode = new VerificationCode();
                    verificationCode.setVerificationCodeCode(UUID.randomUUID().toString());
                    verificationCode.setPhone(phone);
                    verificationCode.setRegCode(code);
                    verificationCode.setIp(ip);
                    verificationCode.setCreateTime(new Date());
                    verificationCodeService.insert(verificationCode);
                }else{
                    //该phone发送过验证码
                    verificationCode.setRegCode(code);
                    verificationCodeService.update(verificationCode);
                }



            }
            else {
                //该ip发送过验证码

                String date = new SimpleDateFormat("yyyyMMdd").format(verificationCodeLimit.getCreateTime());
                String dateNow = new SimpleDateFormat("yyyyMMdd").format(new Date());

                if(date.equals(dateNow)){
                    //该ip今日发送过验证码

                    if(verificationCodeLimit.getCount() > 200){
                        //该ip今日发送验证码超过200个
                        return failed("发送量超过上限");
                    }else{
                        //该ip今日发送验证码未超过200个

                        VerificationCode verificationCode = verificationCodeService.getByPhone(phone);
                        if(verificationCode == null){
                            //该phone未发送过验证码
                            verificationCode = new VerificationCode();
                            verificationCode.setVerificationCodeCode(UUID.randomUUID().toString());
                            verificationCode.setPhone(phone);
                            verificationCode.setRegCode(code);
                            verificationCode.setIp(ip);
                            verificationCode.setCreateTime(new Date());
                            verificationCodeService.insert(verificationCode);
                        }else{
                            //该phone发送过验证码
                            verificationCode.setRegCode(code);
                            verificationCodeService.update(verificationCode);
                        }

                        verificationCodeLimit.setCount(verificationCodeLimit.getCount()+1);
                        verificationCodeLimitService.update(verificationCodeLimit);


                    }


                }else{
                    //该ip今日未发送过验证码

                    VerificationCode verificationCode = verificationCodeService.getByPhone(phone);
                    if(verificationCode == null){
                        //该phone未发送过验证码
                        verificationCode = new VerificationCode();
                        verificationCode.setVerificationCodeCode(UUID.randomUUID().toString());
                        verificationCode.setPhone(phone);
                        verificationCode.setRegCode(code);
                        verificationCode.setIp(ip);
                        verificationCode.setCreateTime(new Date());
                        verificationCodeService.insert(verificationCode);
                    }else{
                        //该phone发送过验证码
                        verificationCode.setRegCode(code);
                        verificationCodeService.update(verificationCode);
                    }

                    verificationCodeLimit.setCount(1);
                    verificationCodeLimit.setCreateTime(new Date());
                    verificationCodeLimitService.update(verificationCodeLimit);

                }

            }




            JSONObject jsonObject1 = new JSONObject();

            return success(jsonObject1);

        }catch (Exception e){
            insertError("/VerificationCode/RegCode",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //找回密码验证码
    @RequestMapping(value = "GetPwdCode",method = RequestMethod.POST)
    public MyResult GetPwdCode(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String phone = jsonObject.getString("phone");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/VerificationCode/GetPwdCode");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            HttpServletRequest request2 =
                    ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();


            String ip = getIpAddress(request);
            if(ip == null || ip.equals("")){
                return failed("ip地址错误");
            }

            if(!isPhone(phone)){
                return failed("手机号格式错误");
            }

            User user = userService.getByPhone(phone);
            if(user == null){
                return failed("手机号未注册");
            }

            String code = Integer.toString(random());

            SendSms sendSms = new SendSms();
            sendSms.SendSms("银秋科技","1102219",phone,code);



            /*
             * 首先判断客户端ip是否发送过验证码
             * 1：未发送过
             *   直接发送
             * 2：发送过
             *   今日是否发送过验证码
             *   2.1今日发送给验证码
             *       发送数量是否超过200个
             *       2.1.1超过了，提示超过上限
             *       2.1.2未超过，直接发送
             *   2.2今日未发送过验证码
             *      直接发送
             *
             * */



            VerificationCodeLimit verificationCodeLimit = verificationCodeLimitService.getByIP(ip);

            if(verificationCodeLimit == null){
                //该ip未发送过验证码

                verificationCodeLimit = new VerificationCodeLimit();
                verificationCodeLimit.setVerificationCodeLimitCode(UUID.randomUUID().toString());
                verificationCodeLimit.setIp(ip);
                verificationCodeLimit.setCount(1);
                verificationCodeLimit.setCreateTime(new Date());
                verificationCodeLimitService.insert(verificationCodeLimit);

                VerificationCode verificationCode = verificationCodeService.getByPhone(phone);
                if(verificationCode == null){
                    //该phone未发送过验证码
                    verificationCode = new VerificationCode();
                    verificationCode.setVerificationCodeCode(UUID.randomUUID().toString());
                    verificationCode.setPhone(phone);
                    verificationCode.setGetPwdCode(code);
                    verificationCode.setIp(ip);
                    verificationCode.setCreateTime(new Date());
                    verificationCodeService.insert(verificationCode);
                }else{
                    //该phone发送过验证码
                    verificationCode.setGetPwdCode(code);
                    verificationCodeService.update(verificationCode);
                }



            }else {
                //该ip发送过验证码

                String date = new SimpleDateFormat("yyyyMMdd").format(verificationCodeLimit.getCreateTime());
                String dateNow = new SimpleDateFormat("yyyyMMdd").format(new Date());

                if(date.equals(dateNow)){
                    //该ip今日发送过验证码

                    if(verificationCodeLimit.getCount() > 200){
                        //该ip今日发送验证码超过200个
                        return failed("发送量超过上限");
                    }else{
                        //该ip今日发送验证码未超过200个

                        VerificationCode verificationCode = verificationCodeService.getByPhone(phone);
                        if(verificationCode == null){
                            //该phone未发送过验证码
                            verificationCode = new VerificationCode();
                            verificationCode.setVerificationCodeCode(UUID.randomUUID().toString());
                            verificationCode.setPhone(phone);
                            verificationCode.setGetPwdCode(code);
                            verificationCode.setIp(ip);
                            verificationCode.setCreateTime(new Date());
                            verificationCodeService.insert(verificationCode);
                        }else{
                            //该phone发送过验证码
                            verificationCode.setGetPwdCode(code);
                            verificationCodeService.update(verificationCode);
                        }

                        verificationCodeLimit.setCount(verificationCodeLimit.getCount()+1);
                        verificationCodeLimitService.update(verificationCodeLimit);


                    }


                }else{
                    //该ip今日未发送过验证码

                    VerificationCode verificationCode = verificationCodeService.getByPhone(phone);
                    if(verificationCode == null){
                        //该phone未发送过验证码
                        verificationCode = new VerificationCode();
                        verificationCode.setVerificationCodeCode(UUID.randomUUID().toString());
                        verificationCode.setPhone(phone);
                        verificationCode.setGetPwdCode(code);
                        verificationCode.setIp(ip);
                        verificationCode.setCreateTime(new Date());
                        verificationCodeService.insert(verificationCode);
                    }else{
                        //该phone发送过验证码
                        verificationCode.setGetPwdCode(code);
                        verificationCodeService.update(verificationCode);
                    }

                    verificationCodeLimit.setCount(1);
                    verificationCodeLimit.setCreateTime(new Date());
                    verificationCodeLimitService.update(verificationCodeLimit);

                }

            }




            JSONObject jsonObject1 = new JSONObject();

            return success(jsonObject1);

        }catch (Exception e){
            insertError("/VerificationCode/GetPwdCode",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }



    /*
    生成6位验证码
    */
    private int random() {
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        int[] c = new int[6];
        for (int i = 0; i < 6; i++) {
            c[i] = r.nextInt(9) + 1;
            sb.append(c[i]);
        }
        return Integer.parseInt(sb.toString());
    }



}
